using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using Q.Framework.WebCode;
using Microsoft.Reporting.WebForms;
using System.Configuration;
using Q.Framework.Utility;
using Q.Framework.Extension;
using Q.Framework.Data;
using System.Text;

namespace Q.Framework.WebCode
{
    public class PageBase : System.Web.UI.Page
    {
        public LogExceptionDelegate LoggingException
        {
            get { return Session["LoggingException"] as LogExceptionDelegate; }
            set { Session["LoggingException"] = value; }
        }

        public LogExceptionDelegate ShowException
        {
            get { return Session["ShowException"] as LogExceptionDelegate; }
            set { Session["ShowException"] = value; }
        }

        protected override void OnError(EventArgs e)
        {
            Exception erro = Server.GetLastError();
            if (ShowException != null)
                ShowException(erro);
        }

        protected override void RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
        {
            MasterPageBase master = (MasterPageBase)base.Page.Master;

            try
            {
                base.RaisePostBackEvent(sourceControl, eventArgument);
            }
            catch (Exception e)
            {
                DoExeption(e, master);
            }
        }

        public virtual void DoExeption(Exception erro, MasterPageBase master)
        {
            if (IsPostBack)
            {
                if (master != null)
                {
                    if (erro.GetType() == typeof(ValidationException))
                    {
                        JavaScriptAdd.MessageBoxShow(this, erro.Message.ToString());
                    }
                    else
                    {
                        if (LoggingException != null)
                            LoggingException(erro);

                        if (ShowException != null)
                            ShowException(erro);
                        else
                            JavaScriptAdd.MessageBoxShow(this, erro.Message);
                    }

                }
            }
        }

        protected void PageBasePage_Load(EventArgs e)
        {

        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }

        public void Redirect(String page)
        {
            Response.Redirect(page, false);
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }

        public void Redirect(String page, Int32 ID)
        {
            Response.Redirect(String.Format("{0}?ID={1}", page, ID), false);
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }

        public void Redirect(String page, String[] parameters)
        {
            String param = "";

            foreach (String item in parameters)
            {
                param += String.Format("{0}&", item);
                param = param.Substring(0, param.Length - 1);
            }

            Response.Redirect(String.Format("{0}?Param={1}", page, param), false);
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }

        /// <summary>
        /// Redireciona para Página Inicial
        /// </summary>
        public void Redirect()
        {
            Response.Redirect("~/Default.aspx");
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            return;
        }

        public String GetPage()
        {
            return this.Page.Request.Url.Segments.Last();
        }

        public virtual void MessageBox(String Message)
        {

            JavaScriptAdd.RegisterStartupScript(this, "Message", new StringBuilder(String.Format("<script>alert('{0}');</script>", Message)));
            //WebCode.MessageBox.Show(Message, WebCode.MessageBox.MessageType.Info);
        }

        public virtual void MessageBoxAndRedirect(String Message, String Url)
        {
            JavaScriptAdd.RegisterStartupScript(this, "Message", new StringBuilder(String.Format("<script>alert('{0}'); window.location.href = '{1}';</script>", Message, Url)));
            //WebCode.MessageBox.Show(Message, WebCode.MessageBox.MessageType.Info, Url);
        }

        public void ShowReport(Microsoft.Reporting.WebForms.ReportViewer Report, Boolean RedirectIndexPage = false, String PagePathRedirect = null)
        {
            ShowReport(Report, null, RedirectIndexPage: RedirectIndexPage, PagePathRedirect: PagePathRedirect);
        }

        public void ShowReport(Microsoft.Reporting.WebForms.ReportViewer Report, String ReportPath, Boolean RedirectIndexPage = false, String PagePathRedirect = null)
        {
            Session["ReportSession"] = null;

            if (!ReportPath.IsNullOrWhiteSpace())
                Report.LocalReport.ReportPath = ReportPath;

            Session.Add("ReportSession", Report);

            JavaScriptAdd.WindowReportOpen(this);

            if (RedirectIndexPage || !PagePathRedirect.IsNullOrWhiteSpace())
            {
                String page = "~/Default.aspx";

                if (!PagePathRedirect.IsNullOrWhiteSpace())
                    page = PagePathRedirect;

                Response.AddHeader("Refresh", "0.001;URL=" + ResolveUrl(page));
            }
        }

        public void ShowReportDefault(Microsoft.Reporting.WebForms.ReportViewer Report)
        {
            Session["ReportSession"] = null;

            ReportParameter[] reportParams = new ReportParameter[1];
            reportParams[0] = new ReportParameter("TituloRelatorio", Session["OpcaoMigalha"].ToString());

            Report.LocalReport.SetParameters(reportParams);

            Session.Add("ReportSession", Report);

            JavaScriptAdd.WindowReportOpen(this);
        }
    }
}